<template>
  <n-grid cols="1 s:1 m:1 l:4 xl:4 2xl:4" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formParams" :rules="rules" ref="formRef">
        <n-form-item label="小程序名称" path="x_name">
          <n-input v-model:value="formParams.x_name" placeholder="请输入小程序名称" />
        </n-form-item>

        <n-form-item label="小程序描述" path="x_desc">
          <n-input v-model:value="formParams.x_desc" placeholder="请输入小程序描述" />
        </n-form-item>

        <n-form-item label="小程序appid" path="appid">
          <n-input placeholder="请输入小程序appid" v-model:value="formParams.appid" />
        </n-form-item>

        <n-form-item label="小程序秘钥" path="appscret">
          <n-input placeholder="请输入小程序秘钥" v-model:value="formParams.appscret" />
        </n-form-item>

        <n-form-item label="商户号" path="mch_id">
          <n-input placeholder="请输入商户号" v-model:value="formParams.mch_id" />
        </n-form-item>

        <n-form-item label="微信服务ID" path="service_id">
          <n-input placeholder="请输入微信服务ID" v-model:value="formParams.service_id" />
        </n-form-item>

        <n-form-item label="商户api秘钥" path="mch_key">
          <n-input placeholder="请输入商户api秘钥" v-model:value="formParams.mch_key" />
        </n-form-item>

        <n-form-item label="商户简称" path="body">
          <n-input placeholder="请输入商户简称" v-model:value="formParams.body" />
        </n-form-item>

        <n-form-item label="商户证书序列号" path="serinal_no">
          <n-input placeholder="请输入商户证书序列号" v-model:value="formParams.serinal_no" />
        </n-form-item>
        
        <!-- <n-form-item label="商户apiclientcert" path="apiclient_cert">
          <n-input
            v-model:value="formParams.apiclient_cert"
            type="textarea"
            placeholder="请输入商户apiclientcert"
          />
        </n-form-item> -->

        <n-form-item label="商户apiclientcert" path="apiclient_cert">
          <n-upload
            :action="`${uploadUrl1}/api/common/upload`"
            @finish="handleFinish"
            v-model:file-list="certFileList"
            max="1"
            name='file'
          >
            <n-button>上传文件</n-button>
          </n-upload>
        </n-form-item>

        <!-- <n-form-item label="商户apiclientkey" path="private_key">
          <n-input
            v-model:value="formParams.private_key"
            type="textarea"
            placeholder="请输入商户apiclientkey"
          />
        </n-form-item> -->
        <n-form-item label="商户apiclientkey" path="private_key">
          <n-upload
            :action="`${uploadUrl1}/api/common/upload`"
            @finish="handleFinishkey"
            v-model:file-list="keyFileList"
            max="1"
            name='file'
          >
            <n-button>上传文件</n-button>
          </n-upload>
        </n-form-item>

        <n-form-item label="Logo" path="image">
          <BasicUpload
              :action="`${uploadUrl1}/api/common/cosupdate`"
              :width="100"
              :height="100"
              name="file"
              @uploadChange="changeSitePicture"
              :max="1"
              :maxSize="10"
              v-model:value="image"
              helpText="单个文件不超过10MB，最多只能上传1个文件"
          />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" :loading="subLoading" @click="formSubmit">更新小程序信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import { webconfigEdit,webconfiginfo } from '@/api/webconfig/index';
  import { useGlobSetting } from '@/hooks/setting';
  import type { UploadFileInfo } from 'naive-ui'
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadUrl1 = uploadUrl;
  const image = ref([]);
  const certFileList = ref([{}]);
  const keyFileList = ref([{}]);
  
  const rules: FormRules = {
    x_name: {
      required: true,
      message: '请输入网站名称',
      trigger: 'blur',
    },
    appid: {
      required: true,
      message: '请输入小程序appid',
      trigger: 'blur',
    },
    appscret: {
      required: true,
      message: '请输入小程序appscret',
      trigger: 'blur',
    },
  };

  const defaultValueRef = () => ({
    x_name: '',
    x_desc: '',
    appid: '',
    appscret: '',
    image: '',
    mch_id: '',
    mch_key: '',
    body: '',
    serinal_no: '',
    apiclient_cert: '',
    private_key: '',
    service_id: '',
  });

  const message = useMessage();
  const formRef: any = ref(null);
  const subLoading = ref(false);
  const formParams = ref(defaultValueRef());

  const handleFinish = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    let res = JSON.parse((event?.target as XMLHttpRequest).response);
    const ext = file.name.split('.')[1]
    file.name = `商户apiclientcert.${ext}`
    formParams.value.apiclient_cert = res.data.path;
    return file;
  }

  const handleFinishkey = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    let res = JSON.parse((event?.target as XMLHttpRequest).response);
    const ext = file.name.split('.')[1]
    file.name = `商户apiclientkey.${ext}`
    formParams.value.private_key = res.data.path;
    return file;
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        formParams.value.image = image.value[0];
        webconfigEdit(formParams.value).then((_) => {
          message.success('更新成功');
        });
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  function getInfo() {
    webconfiginfo({}).then((res) => {
      const params = {
        x_name: res.x_name,
        x_desc: res.x_desc,
        appid: res.appid,
        appscret: res.appscret,
        mch_id: res.mch_id,
        mch_key: res.mch_key,
        body: res.body,
        serinal_no: res.serinal_no,
        apiclient_cert: res.apiclient_cert,
        private_key: res.private_key,
        service_id: res.service_id,
      };
      image.value = res.image;
      certFileList.value = [];
      if(res.apiclient_cert != '' && res.apiclient_cert != null){
        certFileList.value.push({
          id: 1,
          name: '商户apiclientcert.pem',
          status: 'finished',
        });
      }
      
      keyFileList.value = [];
      if(res.private_key != '' && res.private_key != null){
        keyFileList.value.push({
          id: 1,
          name: '商户apiclientkey.pem',
          status: 'finished',
        });
      }
      
      formParams.value = Object.assign(formParams.value, params);
    });
  }

  function changeSitePicture(file){
    image.value = file;
  }

  onMounted(async () => {
    getInfo();
  });
</script>
